#!/bin/bash

# 站在pack目录
pack_dir=.
prj_dir=..

source ${prj_dir}/project.conf

# 创建
MK="mkdir -p"
# 复制、覆盖
CP="cp -f"


# 先进行代码编译后与打包发送前的准备工作
echo -e "\n打包[脚本，库，配置，可执行程序,...]"

# 打包文件名
prj_base_file="${pack_dir}/base"
prj_pkg_file="${pack_dir}/package"
prj_root_file="${prj_pkg_file}/files"

# 创建目录
${MK} ${prj_root_file}
${MK} ${prj_root_file}${prj_conf_path}
${MK} ${prj_root_file}${prj_app_path}
${MK} ${prj_root_file}${prj_startup_path}
${MK} ${prj_root_file}${prj_com_lib_path}
${MK} ${prj_root_file}${prj_uninstall_path}

# 复制脚本、配置
${CP} ${prj_dir}/${prj_conf_sh} 			${prj_root_file}${prj_conf_path}
# 复制并重命名适用于设备端的精简配置文件，设备不需要完全的配置。上面是完整版的
#${CP} ${prj_base_file}/${prj_device_conf_sh} 	${prj_root_file}${prj_conf_path}/${prj_conf_sh}

${CP} ${prj_base_file}/${prj_install_sh} 		${prj_pkg_file}
${CP} ${prj_base_file}/${prj_startup_sh} 		${prj_root_file}${prj_startup_path}
${CP} ${prj_base_file}/${prj_uninstall_sh} 		${prj_root_file}${prj_uninstall_path}


# 复制可执行程序、动态依赖库
for index in ${app_on_list}
do
	app=`echo ${app_list}|awk -F ' ' '{print $'$index'}'`
	app_local_folder=`echo ${app_local_folder_list}|awk -F ' ' '{print $'$index'}'`
	app_device_folder=`echo ${app_device_folder_list}|awk -F ' ' '{print $'$index'}'`
	
	app_local_dir=${prj_dir}"/code/"${app_local_folder}
	app_file_dir=${prj_root_file}${prj_app_path}/${app_device_folder}/
	
	if [ -d ${app_local_dir} ]
	then
		#echo -e "\n 工程 ${app_local_dir}"
		mkdir -p ${app_file_dir}
		
		#echo "${app_local_dir}/out/${app} ${app_file_dir}"
		cp -f ${app_local_dir}/out/${app} ${app_file_dir}
		cp ${prj_base_file}/${prj_guard_sh} ${app_file_dir}/guard_${app}.sh
		#复制库，加-d选项
		if [ -f ${app_local_dir}/lib/*.so* ]; then
			cp -df ${app_local_dir}/lib/*.so* ${prj_root_file}${prj_com_lib_path}
		fi
		
	else
		echo "error: path does not exist ${app_local_dir}"
		
	fi

done


if [ -f ${prj_dir}/${prj_com_code_path}/lib/*.so* ]; then
	cp -df ${prj_dir}/${prj_com_code_path}/lib/*.so* ${prj_root_file}${prj_com_lib_path}
fi


# 再打包
tar -czf ${pack_dir}/package.tar ${pack_dir}/package
cat ${prj_base_file}/${prj_unpack_sh} ${pack_dir}/package.tar > ${pack_dir}/${pack_name}
chmod 777 ${pack_dir}/${pack_name}

# chown root ${pack_dir}}/${pack_name}

rm -rf ${pack_dir}/package
rm -rf ${pack_dir}/package.tar

echo "打包结束"
echo -e "version:${VER}\n"
